By default Apex code executes without checking permissions. Hence the code will not enforce field level security, sharing rules and user
permissions during execution of Apex code in Triggers, Classes and Controllers. This creates the risk that unauthorized users may get access to
sensitive data records or fields.
It is possible to specify different level of sharing via the keywords "with sharing", "without sharing" or "inherited sharing". The last two should
be used very carefully as they can create security risks.
This rule raises an issue whenever a DML, SOSL or SOQL query is executed in a class marked as without sharing
or inherited
sharing
.
Ask Yourself Whether
- this code gives access to or modifies restricted records.
- this code may be executed by users who shouldn’t have access to those records.
- if the class is marked as
inherited sharing
, it may be called by a class marked as without sharing
.
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
- Use
with sharing
whenever possible.
- Use
without sharing
only after checking that the code is not accessible to unauthorized users.
- Use
inherited sharing
only when all calling without sharing
classes are safe.
Sensitive Code Example
public without sharing class MyClass {
List<List<SObject>> sList = [FIND 'TEST' IN ALL FIELDS
RETURNING Case(Name), Contact(FirstName,LastName)]; // Sensitive
}
public inherited sharing class MyClass {
List<Case> lstCases = new List<Case>();
for(Case c:[SELECT Id, Status FROM Case WHERE Status = 'In Progress']){ // Sensitive
c.Status = 'Closed';
lstCasesToBeUpdated.add(c);
}
Update lstCasesToBeUpdated; // Sensitive
}
Compliant Solution
public with sharing class MyClass { // Compliant
List<Case> lstCases = new List<Case>();
for(Case c:[SELECT Id FROM Case WHERE Status = 'In Progress']){
// ...
}
}
See